package cn.xshi.actuator.util;

import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Desc SDKUtil
 * @Author 邓纯杰
 * @CreateTime 2017-09-12 10:11:56
 */
@Component
public class ActuatorSDKUtil {

    @Resource
    Environment environment;

    /**
     * java c命令
     * @return
     */
    public static String javaC(){
        StringBuilder sb = null;
        try {
            Process p = Runtime.getRuntime().exec(new String[]{"java", "-version"});
            InputStreamReader inputStreamReader = new InputStreamReader(p.getErrorStream());
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            sb = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
            bufferedReader.close();
            p.destroy();
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取当前应用进程id
     * @return
     */
    public static String  getPid(){
        String name = ManagementFactory.getRuntimeMXBean().getName();
        String pid = name.split("@")[0];
        return  pid;
    }

    /**
     * 去掉数组中空项
     *
     * @param olds
     * @return news
     */
    public static String[] trim(String[] olds) {
        if (olds ==null ||olds.length == 0){
            return olds;
        }
        List<String> list = new ArrayList<>();
        for (String old : olds) {
            if (old != null && !"".equals(old)) {
                list.add(old);
            }
        }
        String[] news = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            news[i] = list.get(i);
        }
        return news;
    }

    /**
     * 匹配字符出现次数
     * @param srcText
     * @param findText
     * @return
     */
    public static int appearNumber(String srcText, String findText) {
        int count = 0;
        Pattern p = Pattern.compile(findText);
        Matcher m = p.matcher(srcText);
        while (m.find()) {
            count++;
        }
        return count;
    }
    //获取项目的根路径
    public final static String classPath;

    static {
        //获取的是classpath路径，适用于读取resources下资源
//        classPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        classPath = System.getProperty("user.dir");
    }

    /**
     * 项目根目录
     */
    public static String getRootPath() {
        return RootPath("");
    }

    /**
     * 自定义追加路径
     */
    public static String getRootPath(String u_path) {
        return RootPath("/" + u_path);
    }

    /**
     * 私有处理方法
     */
    private static String RootPath(String u_path) {
        String rootPath = "";
        //windows下
        if ("\\".equals(File.separator)) {
            rootPath = classPath + u_path;
            rootPath = rootPath.replaceAll("/", "\\\\");
            if (rootPath.substring(0, 1).equals("\\")) {
                rootPath = rootPath.substring(1);
            }
        }
        //linux下
        if ("/".equals(File.separator)) {
            rootPath = classPath + u_path;
            rootPath = rootPath.replaceAll("\\\\", "/");
        }
        return rootPath;
    }

    /**
     * 字节转换
     * @param size 字节大小
     * @return 转换后值
     */
    public static String computeFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else {
            return String.format("%d B", size);
        }
    }


    public String getProjectName(){
        String projectName = environment.getProperty("spring.application.name");
        if(null == projectName || "".equals(projectName)){
            projectName = environment.getProperty("project.name");
        }
        if(null == projectName || "".equals(projectName)){//增加通过app-id获取
            projectName = environment.getProperty("app.id");
        }
        return projectName;
    }

    /**
     * 获取系统运行环境
     * @return
     */
    public String getEnviron(){
        String environ = environment.getProperty("env");
        if(null == environ || "".equals(environ)){
            environ = environment.getProperty("spring.profiles.active");
        }
        if(null == environ || "".equals(environ)){
            environ = "prod";
        }
        return environ;
    }

    /**
     * 判断是否生产环境
     * @return
     */
    public boolean isProd(){
        if("prod".equals(getEnviron()) ||
                "lpt".equals(getEnviron()) ||
                "pro".equals(getEnviron()) ||
                "pre".equals(getEnviron()) ||
                "pred".equals(getEnviron()) ||
                "prep".equals(getEnviron())){//生产
            return true;
        }else{
            return false;//测试包含fat，dev4，test等
        }
    }

    /**
     * 获取端口
     * @return
     */
    public int getLocalPort(){
        return new Integer(environment.getProperty("server.port"));
    }
}
